/****************************************************************
 * Copyright C 2002, Daniele Venzano                            *
 * This code is protected by the GPL License v. 2               *
 * You can find it al http://www.gnu.org                        *
 *                                                              *
 * - 2009-Nov-23: Modified by Brent Smith, to produce a C-based *
 *   array from a psf file.  PSF files can be found with the    *
 *   KBD distribution at:                                       *
 *   http://www.kernel.org/pub/linux/utils/kbd/                 *
 *   - The first argument is the psf file to convert            *
 *   - The second, optional argument is "invert" to invert the  *
 *     rows in each character so that it is compatible with     *
 *     OpenGL's glBitmap(), which expects the first byte to be  *
 *     the bottom row of each character (consistent with        *
 *     OpenGL's definition of the coordinate (0,0) as the       *
 *     bottom left).                                            *
 ****************************************************************/

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE *font;
    unsigned char byte, *chr;
    int filemode;
    char fontheight;
    int i,j;
    int invert = 0;
    
    if(argc > 1)
    {
        font = fopen(argv[1], "r");
        if(font == NULL)
        {
            printf("%s was not found", argv[1]);
            return -1;
        }
        if ((argc > 2) && (strcmp(argv[2],"invert")==0))
            invert = 1;
    }
    else font = stdin;

    byte = fgetc(font);
    if(byte != 0x36)
    {
        printf("%s is not a psf font file", argv[1]);
        return -1;
    }
    byte = fgetc(font);
    if(byte != 0x04)
    {
        printf("%s is not a psf font file", argv[1]);
        return -1;
    }

    filemode = fgetc(font);
    if(filemode == 1 || filemode == 3)
        filemode = 512;
    if(filemode == 0 || filemode == 2)
        filemode = 256;
    fontheight = fgetc(font);

    chr = (unsigned char *)malloc(fontheight);

    printf ("unsigned char letters[][%d] = {\n", fontheight);
    for (i=0; i < filemode; i++)
    {
        printf("\t{ ");
        for (j=0; j < fontheight; j++)
            chr[j] = fgetc(font);
    
        for (j=0; j < fontheight; j++)
            printf("0x%02x%s", (invert) ? chr[fontheight-j-1] : chr[j], 
                               (j == (fontheight-1)) ? " " : ", ");

        printf("}");
        printf("%s", i == (filemode-1) ? "\n" : ",\n");
    }
    printf ("};\n");

    free(chr);

    fclose(font);
    return 0;
}

